<?php
namespace app\common\lib;

use think\Db;

class EventCheck{

    //事件初审、终审
    public static function audit_pass($auditId, $record_add_integral = 0, $first_add_integral = 0,$check_opinion='')
    {
        //判断需要审核任务的状态，并且判断截至时间
        $auditInfo = M('com_integral_prize_buckle')->where('id', $auditId)->find();
        if(!$auditInfo)  return '审核数据不存在!';
        $saveData = [];
        //判断当前人是否为该任务的，审核人
        $userId = session("user_com")['id'];

        switch ($auditInfo['status']) {
            case 0:         //待初审
                if($auditInfo['first_check_user_id'] != $userId)  return '你不是该任务相关初审人，不能审核';
                $saveData['first_check_opinion'] = $check_opinion;
                $saveData['first_check_time'] = time();
                break;
            case 1:         // 1待终审
                if($auditInfo['last_check_user_id'] != $userId)  return '你不是该任务相关终审人，不能审核';
                $saveData['last_check_opinion'] = $check_opinion;
                $saveData['last_check_time'] = time();
                break;
            default:
                return '审核，数据有误！';
                break;
        }

        $saveData['id']     = $auditId;
        $saveData['status'] = $auditInfo['status'] + 1;

        //审核通过
        DB::startTrans();//开启事务
        try{
            M('com_integral_prize_buckle')->update($saveData);
            //终审通过，加分事件
            if( $auditInfo['status'] == 1 ) {
                //奖扣送分
                SendIntegralNew::send($auditId, 3, $first_add_integral, $record_add_integral);

                //记录人
                $data_message[] = [
                    'title' => '您有一条积分奖扣已通过终审',
                    'user_id' => $auditInfo['record_user_id'],
                    'cate_type' => 4,//积分奖扣消息
                    'type' => 3,//积分奖扣
                    'relation_id' => $auditId
                ];
                //初审人
                $data_message[] = [
                    'title' => '您有一条奖扣审核已通过终审',
                    'user_id' => $auditInfo['first_check_user_id'],
                    'cate_type' => 1,//积分奖扣消息
                    'type' => 3,//积分奖扣
                    'relation_id' => $auditId
                ];

                //抄送人
                if (!empty($auditInfo['copy_user_id'])) {
                    $data_message[] = [
                        'title' => '您有一条相关的奖扣已通过终审',
                        'user_id' => $auditInfo['copy_user_id'],
                        'cate_type' => 4,//积分奖扣消息
                        'type' => 3,//积分奖扣
                        'relation_id' => $auditId
                    ];
                }

                //参与人
                $list = M('com_integral_event_relation_users a')
                    ->join('com_integral_prize_buckle_relation_event b', 'a.event_id=b.id', 'left')
                    ->where('b.prize_buckle_id', $auditId)
                    ->field('a.user_id')
                    ->select();
                foreach ($list as $key => $value) {
                    $data_message[] = [
                        'title' => '您有一条参与的积分奖扣已通过终审',
                        'user_id' => $value['user_id'],
                        'cate_type' => 4,//积分奖扣消息
                        'type' => 3,//积分奖扣
                        'relation_id' => $auditId
                    ];
                }
                \app\company\logic\Message::send_message_list($data_message);

            }else{
                //记录人
                $data_message[] = [
                    'title' => '您有一条记录已通过初审',
                    'user_id' => $auditInfo['record_user_id'],
                    'cate_type' => 4,//积分奖扣消息
                    'type' => 3,//积分奖扣
                    'relation_id' => $auditId
                ];
                //终审人
                $data_message[] = [
                    'title' => '您有一条奖扣记录需要您审核(终审)',
                    'user_id' => $auditInfo['last_check_user_id'],
                    'cate_type' => 1,//审核消息
                    'type' => 3,//积分奖扣
                    'relation_id' => $auditId
                ];
                \app\company\logic\Message::send_message_list($data_message);
            }

            DB::commit();//提交
        }catch (\Exception $e){
            DB::rollback();//回滚
            return $e->getMessage();
        }

    }

    //撤回\驳回:删除参与人所得积分,及系统事件
    public static function audit_withdraw($auditInfo){

        $arr = array_keys(SystemEvent::names());

        $event_ids = M('com_integral_prize_buckle_relation_event')->where('prize_buckle_id', $auditInfo['id'])->column('id,event_id,prize_buckle_id','id');

        $tmpEventId = [];                     //系统事件
        $tmpFixeEventId = [];                 //非系统事件
        //callback操作
        foreach ( $event_ids as $event_id ) {
            if(in_array($event_id['event_id'], $arr)){      //系统事件
                $tmpEventId[] = $event_id['id'];
            }else{                              //非系统事件
                $tmpFixeEventId[] = $event_id['id'];
            }
        }

        //积分奖扣事件关联表
        M('com_integral_prize_buckle_relation_event')
            ->where([
                'com_id'=>$auditInfo['com_id'],
                'id'=>['in', $tmpEventId],
            ])
            ->delete();


        $callbackWhere = [
            'com_id'=>$auditInfo['com_id'],
            'event_id'=>['in', array_merge($tmpEventId, $tmpFixeEventId)],
        ];

        //积分奖扣事件参与人关联表
        //获取系统，非系统事件的用户id,a,b分
        $infos = M('com_integral_event_relation_users')
            ->where($callbackWhere)
            ->column('user_id, integral_a, integral_b,piece_rate');

        $user_ids = array_column($infos, 'user_id');

        //积分奖扣事件参与人关联表
        //删除系统事件关联的event_id
        M('com_integral_event_relation_users')
            ->where([
                'com_id'=>$auditInfo['com_id'],
                'event_id'=>['in', $tmpEventId]
            ])
            ->delete();

        //积分记录表
        M('com_integral_log')
            ->where($callbackWhere)
//            ->where('user_id', 'in', $user_ids)
            ->delete();
        foreach ($infos as $key=>$value) {
            if($value['piece_rate']>0){
                $integral_b = $value['integral_b'] * $value['piece_rate'];
                $integral_a = $value['integral_a'] * $value['piece_rate'];
            }else{
                $integral_a = $value['integral_a'];
                $integral_b = $value['integral_b'];
            }
            if($integral_b >0){
                $userUpdate = [
                    'integral_a' => Db::raw('integral_a-' . $integral_a),
                    'integral_b' => Db::raw('integral_b-' . $integral_b),
                ];
            }else{
                $userUpdate = [
                    'integral_a' => Db::raw('integral_a+' . abs($integral_a)),
                    'integral_b' => Db::raw('integral_b+' . abs($integral_b)),
                ];
            }

            M('users')->where('id',$value['user_id'])->update($userUpdate);
        }

    }

    //驳回：

}
